Ext.define('DCApp.controller.Global', {
    extend: 'Ext.app.Controller',
    requires: [
        'DCApp.view.*',
        'Ext.window.*'
    ],
    loadingText: 'Loading...',
    stores: ['Thumbnails','Authors'],

    config: {
        control: {
            'navigation-tree': {
                selectionchange: 'onTreeNavSelectionChange'
            },
            'navigation-breadcrumb breadcrumb': {
                selectionchange: 'onBreadcrumbNavSelectionChange'
            },
            'thumbnails': {
                itemclick: 'onThumbnailClick',
                itemdblclick: 'onThumbnailClick'
            },
            'tool[regionTool]': {
                click: 'onSetRegion'
            },
            'doclist':{
            	openobj:'onOpenObj'
            },
            'docdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'docuklist':{
            	openobj:'onOpenObj'
            },
            'docukdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'paylist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'paydetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'imglist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'imgpanel':{
            	editobj:'onEditObj'
            },
            'imgdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'attachlist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'attachpanel':{
            	editobj:'onEditObj'
            },
            'attachdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'reliclist':{
            	openobj:'onOpenObj'
            },
            'relicdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'ugrouplist':{
            	openobj:'onOpenObj'
            },
            'ugroupdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'ccsynclist':{
            	openobj:'onOpenObj'
            },
            'ccsyncdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'relicuklist':{
            	openobj:'onOpenObj'
            },
            'relicukdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'uuserlist':{
            	openobj:'onOpenObj'
            },
            'uuserdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'thesislist':{
            	openobj:'onOpenObj'
            },
            'giftlist':{
            	openobj:'onOpenObj'
            },
            'figurelist':{
            	openobj:'onOpenObj'
            },
            'figuredetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'figureuklist':{
            	openobj:'onOpenObj'
            },
            'figureukdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'avlist':{
            	openobj:'onOpenObj'
            },
            'buildinglist':{
            	openobj:'onOpenObj'
            },
            'cataloglist':{
            	openobj:'onOpenObj'
            },
            'catalogdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'booklist':{
            	openobj:'onOpenObj'
            },
            'contributionlist':{
            	openobj:'onOpenObj'
            },
            'contributiondetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'contributionuklist':{
            	openobj:'onOpenObj'
            },
            'contributionukdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'bookdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'lemmalist':{
            	openobj:'onOpenObj'
            },
            'lemmalist':{
            	openobj:'onOpenObj'
            }
        },
        refs: {
            viewport: 'viewport',
            navigationTree: 'navigation-tree',
            navigationBreadcrumb: 'navigation-breadcrumb',
            contentPanel: 'contentPanel',
            descriptionPanel: 'descriptionPanel',
            thumbnails: {
                selector: 'thumbnails',
                xtype: 'thumbnails',
                autoCreate: true
            }
        },
        routes  : {
            ':id': {
                action: 'handleRoute',
                before: 'beforeHandleRoute'
            },
            '(:en)detail/:id':{
            	action     : 'showDetail',
            	conditions : {
                    ':id' : '([0-9]+)'
                }
            },
            'paydetail/:id':'showPay',
           // 'docdetail/:id':'showDoc',
            'imgdetail/:id':'showImg',
            'attachdetail/:id':'showAttach',
           // 'relicdetail/:id':'showRelic',
            'thesisdetail/:id':'showThesis',
            'giftdetail/:id':'showGift',
            'buildingdetail/:id':'showBuilding',
            'catalogdetail/:id':'showCatalog',
            'figuredetail/:id':'showFigure' ,
            'avdetail/:id':'showAudioVideo',
            'bookdetail/:id':'showBook',
            //'contributiondetail/:id':'showContribution',
            'lemmadetail/:id':'showLemma',
            'agdetail/:id':'showBaseAllograph',
            'docukdetail/:id':'showDocuk',
            'relicukdetail/:id':'showRelicuk',
            'ccsyncdetail/:id':'showCcsync',
            'uuserdetail/:id':'showUUser',
            'ugroupdetail/:id':'showUGroup'
        }
    },
    setOrigUri:function(uri){
    	this.ouri = uri;
    },
    getOrigUri:function(){
    	return this.ouri;
    },
    showDetail:function(p1,p2,p3){
    	//console.log('showDetail:'+p1+":"+p3);
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var pdetail = p1+'detail';
    	if(!DCApp.Cfg.usrInfo){
    		me.setOrigUri(pdetail+'/'+p3);
    		return me.showLogin();
    	}
    	var className = 'DCApp.model.'+Ext.String.capitalize(p1);
    	var modelClass = Ext.ClassManager.get(className);
    	if(!modelClass)
    		return false;
    	var pm={};
    	pm[modelClass.idProperty||'id']=p3;
    	var obj = modelClass.create(pm);
    	//var img = DCApp.model.Image.create({imageId:id});
    	var me=this;
    	//Uses the configured RestProxy to make a GET request to /users/123
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,p3,pdetail);
    	    }
    	});
    	
    },
    showBaseAllograph:function(id){
    	//on new doc 真实系统此处会new一个entity,并打开该rec
    	var obj = DCApp.model.BaseAllograph.create({id:id});
    	var me=this;
    	//Uses the configured RestProxy to make a GET request to /users/123
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.onViewBaseAllograph(null,rec,id);
    	    }
    	});
    },
    onViewBaseAllograph: function (view, rec, id) {
    	this.viewObj(rec,id,'agdetail');
    },
    
    onEditObj:function(vw,rec){
    	var vm = vw.getViewModel();
     	var nd = vm.type.replace('list','detail');
     	var ds = vw.getStore();
        var className = Ext.ClassManager.getNameByAlias('widget.'+nd);
        var ViewClass = Ext.ClassManager.get(className);

    	var cmp = new ViewClass({viewModel: {
            data: {
            	theObj: rec,
            	showprev:false,
            	shownext:false,
            	showsave:true,
            	showreturn:false
            }
        }});    
    	
     	var dlg = Ext.create('Ext.window.Window', {
     		scrollable :true,
     		maximized:true,
     		//layout: 'fit',
     		items:[cmp]
    	});
     	dlg.show();
    },
    onOpenObj:function(vw,rec,rd){
    	//var vm = vw.getViewModel();
    	//var nd = this.getView().getXType().replace('detail','list');
    	var nl = vw.getXType();
     	var nd = nl.replace('list','detail');
     	var ds = vw.getStore();
     	var pos = ds.indexOf(rec);
     	
     	this.open_info={list:vw,rec:rec,
     		nd:nd,nl:nl,
     		rec_prev : ds.getAt(pos-1),
     		rec_next : ds.getAt(pos+1),
     		scroll_y : vw.getView().getScrollY()
     	};
    	this.redirectTo(nd + '/'+ rec.id);
    },
    objNext:function(){
    	//destroy current detail panel
    	var contentPanel = this.getContentPanel();
    	contentPanel.removeAll(true);
    	
    	var inf = this.open_info;    	
     	var ds = inf.list.getStore();
     	var rec=inf.rec_next;
     	var pos = ds.indexOf(rec);
     	inf.rec_prev= inf.rec;
     	inf.rec=inf.rec_next;
     	inf.rec_next = ds.getAt(pos+1);
    	this.redirectTo(inf.nd + '/'+ rec.id);
    },
    objPrev:function(){
    	//destroy current detail panel
    	var contentPanel = this.getContentPanel();
    	contentPanel.removeAll(true);

    	var inf = this.open_info;    	
     	var ds = inf.list.getStore();
     	var rec=inf.rec_prev;
     	var pos = ds.indexOf(rec);
     	inf.rec_next= inf.rec;
     	inf.rec=inf.rec_prev;
     	inf.rec_prev = ds.getAt(pos-1);
    	this.redirectTo(inf.nd + '/'+ rec.id);
    },

    showAudioVideo:function(id){
    	//on new doc 真实系统此处会new一个entity,并打开该rec
    	var obj = DCApp.model.AudioVideo.create({id:id});
    	var me=this;
    	//Uses the configured RestProxy to make a GET request to /users/123
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,id,'avdetail');
    	    }
    	});
    },
    showFigure:function(id){
    	//on new doc 真实系统此处会new一个entity,并打开该rec
    	var obj = DCApp.model.Figure.create({objId:id});
    	var me=this;
    	//Uses the configured RestProxy to make a GET request to /users/123
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,id,'figuredetail');
    	    }
    	});
    },
    showFigureuk:function(id){
    	//on new doc 真实系统此处会new一个entity,并打开该rec
    	var obj = DCApp.model.FigureUk.create({objId:id});
    	var me=this;
    	//Uses the configured RestProxy to make a GET request to /users/123
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,id,'figureukdetail');
    	    }
    	});
    },
    showImg:function(id){
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var img = DCApp.model.Image.create({imageId:id});
    	var me=this;
    	//Uses the configured RestProxy to make a GET request to /users/123
    	img.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,id,'imgdetail');
    	    }
    	});
    },
    showAttach:function(id){
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var obj = DCApp.model.CeAttachment.create({id:id});
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,id,'attachdetail');
    	    }
    	});
    },
    showDoc:function(id){
    	//on new doc 真实系统此处会new一个entity,并打开该rec
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var Doc = DCApp.model.Doc.create({id:id});
    	// 获取一个文物
    	Doc.load({
    		scope: this,
    	    success: function(rec) {
    	    	me.viewObj(rec,id,'docdetail');
    	    }
    	});
    },
    showDocuk:function(id){
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var DocUk = DCApp.model.DocUk.create({id:id});
    	// 获取一个文物
    	DocUk.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,id,'docukdetail');
    	    }
    	});
    },
    showRelic:function(id){
    	//TODO 此处应当区分是从grid双击打开，还是从地址栏加载, 双击打开应从缓存加载record，并显示“下一条”，“上一条”菜单，地址栏加载则不显示
    	//on new doc 真实系统此处会new一个entity,并打开该rec
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var Relic = DCApp.model.Relic.create({objId:id});
    	// 获取一个文物
    	Relic.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec, id,'relicdetail');
    	    }
    	});
    },
    showUUser:function(id){
    	//TODO 此处应当区分是从grid双击打开，还是从地址栏加载, 双击打开应从缓存加载record，并显示“下一条”，“上一条”菜单，地址栏加载则不显示
    	//on new doc 真实系统此处会new一个entity,并打开该rec
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var UUser = DCApp.model.UUser.create({id:id});
    	// 获取一个文物
    	UUser.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec, id,'uuserdetail');
    	    }
    	});
    },
    showUGroup:function(id){
    	//TODO 此处应当区分是从grid双击打开，还是从地址栏加载, 双击打开应从缓存加载record，并显示“下一条”，“上一条”菜单，地址栏加载则不显示
    	//on new doc 真实系统此处会new一个entity,并打开该rec
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var UGroup = DCApp.model.UGroup.create({id:id});
    	// 获取一个文物
    	UGroup.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec, id,'ugroupdetail');
    	    }
    	});
    },

    showCcsync:function(id){
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var CcSync = DCApp.model.CcSync.create({id:id});
    	CcSync.load({
    		scope: this,
    	    success: function(rec) {
    	    	me.viewObj(rec,id,'ccsyncdetail');
    	    }
    	});
    },
    showRelicuk:function(id){
    	//TODO 此处应当区分是从grid双击打开，还是从地址栏加载, 双击打开应从缓存加载record，并显示“下一条”，“上一条”菜单，地址栏加载则不显示
    	//on new doc 真实系统此处会new一个entity,并打开该rec
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var Relic = DCApp.model.RelicUk.create({objId:id});
    	// 获取一个文物
    	Relic.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec, id,'relicukdetail');
    	    }
    	});
    },
    showBook:function(id){
    	//on new book 真实系统此处会new一个entity,并打开该rec
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var Book = DCApp.model.Book.create({objId:id});
    	//Uses the configured RestProxy to make a GET request to /users/123
    	Book.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec, id,'bookdetail');
    	    }
    	});
    },
    showContribution:function(id){
    	//on new contribution 真实系统此处会new一个entity,并打开该rec
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var obj = DCApp.model.Contribution.create({conId:id});
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec, id,'contributiondetail');
    	    }
    	});
    },
    showLemma:function(id){
    	//on new lemma 真实系统此处会new一个entity,并打开该rec
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var obj = DCApp.model.Lemma.create({id:id});
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec, id,'lemmadetail');
    	    }
    	});
    },
    showThesis:function(id){
    	var obj = DCApp.model.Thesis.create({thesisId:id});
    	var me = this;
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec, id,'thesisdetail');
    	    }
    	});
    },
    showGift:function(id){
    	var obj = DCApp.model.CeGift.create({id:id});
    	var me=this;
    	//Uses the configured RestProxy to make a GET request to /users/123
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,id,'giftdetail');
    	    }
    	});
    }, 
    showBuilding:function(id){
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var obj = DCApp.model.Building.create({objId:id});
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,id,'buildingdetail');
    	    }
    	});
    },
    showPay:function(id){
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var obj = DCApp.model.CcPay.create({id:id});
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,id,'paydetail');
    	    }
    	});
    },
    showCatalog:function(id){
    	var me=this;
    	if(me.open_info){
    		return me.openObj();
    	}
    	var obj = DCApp.model.ThesisCatalog.create({catalogId:id});
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,id,'catalogdetail');
    	    }
    	});
    },
        
    
    viewObj:function(rec,id,detail_type){
    	var contentPanel = this.getContentPanel();
    	contentPanel.removeAll(true);
        var className = Ext.ClassManager.getNameByAlias('widget.'+detail_type);
        var ViewClass = Ext.ClassManager.get(className);

    	var cmp = new ViewClass({viewModel: {
            data: {
            	theObj: rec,
            	showprev:false,
            	shownext:false,
            	showsave:false,
            	showreturn:false
            }
        }});    	
    	contentPanel.add(cmp);
    	Ext.resumeLayouts(true);
    },
    openObj:function(){
    	var contentPanel = this.getContentPanel();
    	contentPanel.removeAll(false);
    	var list = this.open_info.list;
    	var cmp = list.detail;
    	if(!cmp){
	        var className = Ext.ClassManager.getNameByAlias('widget.'+this.open_info.nd);
	        var ViewClass = Ext.ClassManager.get(className);
	
	    	cmp = new ViewClass({viewModel: {
	            data: {
	            	theObj: this.open_info.rec,
	            	showprev:Boolean(this.open_info.rec_prev),
	            	shownext:Boolean(this.open_info.rec_next),
	            	showsave:true,
	            	showreturn:true
	            }
	        }});    
	       // list.detail=cmp;
    	}else{
//    		cmp.setViewModel({
//	            data: {
//	            	theObj: this.open_info.rec
//	            }
//	        });
//    		cmp.setData({
//	            	theObj: this.open_info.rec
//	            });
	        cmp.getViewModel().bind({data: {
	            	theObj: this.open_info.rec
	            }},function(d){
	        	console.log(d);
	        });
	        cmp.updateLayout();
    	}
        //建立list与对应detail的双向指向，以支持detail的返回 下一条，detail的直接复用。
        
    	contentPanel.add(cmp);
    	//Ext.resumeLayouts(true);
    },

    beforeHandleRoute: function(id, action) {
        var me = this,
            node = Ext.StoreMgr.get('navigation').getNodeById(id);

        if (node) {
            //resume action
            action.resume();
        } else {
            Ext.Msg.alert(
                'Route Failure',
                'The view for ' + id + ' could not be found. You will be taken to the application\'s start',
                function() {
                    me.redirectTo(me.getApplication().getDefaultToken());
                }
            );

            //stop action
            action.stop();
        }
    },

    handleRoute: function(id) {
        var me = this;
    	if(!me.user){
    		me.setOrigUri(id);
    		me.showLogin();
    		return false;
    	}
       
        var navigationTree = me.getNavigationTree(),
            navigationBreadcrumb = me.getNavigationBreadcrumb(),
            store = Ext.StoreMgr.get('navigation'),
            node = store.getNodeById(id),
            contentPanel = me.getContentPanel(),
            themeName = Ext.themeName,
            thumbnails = me.getThumbnails(),
            hasTree = navigationTree && navigationTree.isVisible(),
            cmp, className, ViewClass, clsProto, thumbnailsStore;

        Ext.suspendLayouts();

        if (node.isLeaf()) {
        	var b_return=this.open_info && id== this.open_info.nl;
            if (thumbnails.ownerCt) {
                contentPanel.remove(thumbnails, false); // remove thumbnail view without destroying
            } else {
            	//如果是从detail返回list，则缓存detail panel
                //contentPanel.removeAll(!b_return);
            	contentPanel.removeAll(true);
            }

            if (hasTree) {
                // Focusing explicitly brings it into rendered range, so do that first.
                navigationTree.getView().focusNode(node);
                navigationTree.getSelectionModel().select(node);
            } else {
                navigationBreadcrumb.setSelection(node);
            }

			if(b_return){
				cmp = this.open_info.list;
				//refrest list
				//var ds = cmp.getStore();
				//ds.reload();
				//cmp.updateLayout();
				
			}else{
	            className = Ext.ClassManager.getNameByAlias('widget.' + id);
	            ViewClass = Ext.ClassManager.get(className);
	            clsProto = ViewClass.prototype;
	
	            if (clsProto.themes) {
	                clsProto.themeInfo = clsProto.themes[themeName];
	
	                if (themeName === 'gray') {
	                    clsProto.themeInfo = Ext.applyIf(clsProto.themeInfo || {}, clsProto.themes.classic);
	                } else if (themeName !== 'neptune' && themeName !== 'classic') {
	                    if (themeName === 'crisp-touch') {
	                        clsProto.themeInfo = Ext.applyIf(clsProto.themeInfo || {}, clsProto.themes['neptune-touch']);
	                    }
	                    clsProto.themeInfo = Ext.applyIf(clsProto.themeInfo || {}, clsProto.themes.neptune);
	                }
	                // <debug warn>
	                // Sometimes we forget to include allowances for other themes, so issue a warning as a reminder.
	                if (!clsProto.themeInfo) {
	                    Ext.log.warn ( 'Example \'' + className + '\' lacks a theme specification for the selected theme: \'' +
	                        themeName + '\'. Is this intentional?');
	                }
	                // </debug>
	            }
	
	            cmp = new ViewClass();
			}
           // contentPanel.setLayout('fit');
            contentPanel.add(cmp);

            this.updateTitle(node);
            
            if(!b_return)
            	Ext.resumeLayouts(true);
            else{
            	Ext.resumeLayouts(true);
            	//偏移1像素,否则gridview不刷新
            	cmp.getView().scrollTo(0,this.open_info.scroll_y+1);
            }

            if (cmp.floating) {
                cmp.show();
            }
        } else {
            // Only attempt to select the node if the tree is visible
            if (hasTree) {
                if (id !== 'all') {
                    // If the node is the root (rootVisible is false), then
                    // Focus the first node in the tree.
                    navigationTree.ensureVisible(node.isRoot() ? store.getAt(0) : node, {
                        select: true,
                        focus: true
                    });
                }
            }
            // Ensure that non-leaf nodes are still highlighted and focused.
            else {
                navigationBreadcrumb.setSelection(node);
            }
            thumbnailsStore = me.getThumbnailsStore();
            thumbnailsStore.removeAll();
            thumbnailsStore.add(node.childNodes);
            if (!thumbnails.ownerCt) {
                contentPanel.removeAll(true);
            }
            //contentPanel.setLayout('auto');
            contentPanel.add(thumbnails);
            this.updateTitle(node);
            Ext.resumeLayouts(true);
        }
    },
    
    updateTitle: function(node) {
        var text = node.get('text'),
            title = node.isLeaf() ? (node.parentNode.get('text') + ' - ' + text) : text;
        
        this.getContentPanel().setTitle(title);
        document.title = document.title.split(' - ')[0] + ' - ' + text;
    },


    exampleRe: /^\s*\/\/\s*(\<\/?example\>)\s*$/,
    themeInfoRe: /this\.themeInfo\.(\w+)/g,

    renderCodeMarkup: function(loader, response) {
        var code = this.processText(response.responseText, loader.themeInfo);
        // Passed in from the block above, we keep the proto cloned copy.
        loader.resource.html = code;
        loader.getTarget().setHtml(code);
        //prettyPrint();
        return true;
    },

    processText: function (text, themeInfo) {
        var lines = text.split('\n'),
            removing = false,
            keepLines = [],
            len = lines.length,
            exampleRe = this.exampleRe,
            themeInfoRe = this.themeInfoRe,
            encodeTheme = function (text, match) {
                return Ext.encode(themeInfo[match]);
            },
            i, line, code;

        for (i = 0; i < len; ++i) {
            line = lines[i];
            if (removing) {
                if (exampleRe.test(line)) {
                    removing = false;
                }
            } else if (exampleRe.test(line)) {
                removing = true;
            } else {
                // Replace "this.themeInfo.foo" with the value of "foo" properly encoded
                // for JavaScript (otherwise strings would not be quoted).
                line = line.replace(themeInfoRe, encodeTheme);
                keepLines.push(line);
            }
        }

        code = Ext.htmlEncode(keepLines.join('\n'));
        return '<pre class="prettyprint">' + code + '</pre>';
    },

    onSetRegion: function (tool) {
        var panel = tool.toolOwner;

        var regionMenu = panel.regionMenu || (panel.regionMenu =
            Ext.widget({
                xtype: 'menu',
                items: [{
                    text: 'North',
                    checked: panel.region === 'north',
                    group: 'mainregion',
                    handler: function () {
                        panel.setBorderRegion('north');
                    }
                },{
                    text: 'South',
                    checked: panel.region === 'south',
                    group: 'mainregion',
                    handler: function () {
                        panel.setBorderRegion('south');
                    }
                },{
                    text: 'East',
                    checked: panel.region === 'east',
                    group: 'mainregion',
                    handler: function () {
                        panel.setBorderRegion('east');
                    }
                },{
                    text: 'West',
                    checked: panel.region === 'west',
                    group: 'mainregion',
                    handler: function () {
                        panel.setBorderRegion('west');
                    }
                }]
            }));

        regionMenu.showBy(tool.el);
    },

    onTreeNavSelectionChange: function(selModel, records) {
        var record = records[0];

        if (record) {
            this.redirectTo(record.getId());
        }
    },

    onBreadcrumbNavSelectionChange: function(breadcrumb, node) {
        if (node) {
            this.redirectTo(node.getId());
        }
    },

    onThumbnailClick: function(view, node, item, index, e) {
        var navigationTree = this.getNavigationTree();

        // If not using breadcrumb nav, drive the app through the tree's normal selection listener
        // This ensures that the tree is scrolled correctly with the correct node highlighted.
        if (navigationTree && navigationTree.isVisible()) {
            navigationTree.ensureVisible(node, {
                select: true,
                focus: true
            });
        } else {
        	var idd = node.data['idd'];
        	if(idd)
        		idd+='/-1';
            this.redirectTo(idd||node.getId());
        }
    },
    onLogin: function (loginController, user, organization, loginManager) {
        this.login.destroy();
        delete this.login;
        this.loginManager = loginManager;
        this.organization = organization;
        this.user = user;
        
        this.showUI();
    },
    
    showUI: function() {
    	var me = this;
        me.viewport = new DCApp.view.main.Main({
            session: this.session,
            viewModel: {
                data: {
                    currentOrg: this.organization,
                    currentUser: this.user
                }
            }
        });
        var url = me.getOrigUri()||'all';
        me.redirectTo(url,true);
    },
    showLogin:function(){
    	if(this.login)
    		return;
        this.login = new DCApp.view.login.Login({
            session: this.session,
            autoShow: true,
            listeners: {
                scope: this,
                login: 'onLogin'
            }
        });
    },
    onLaunch: function () {
    	this.showLogin();    	
    }

});
